/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChangePasswordDialog.java
 *
 * Created on 20/10/2011, 23:14:56
 */
package br.com.mocamorena.view.dialog;

import br.com.mocamorena.control.ControleUsuario;
import br.com.mocamorena.exception.InputValidationException;
import br.com.mocamorena.exception.PersistenciaException;
import br.com.mocamorena.model.Usuario;
import br.com.mocamorena.view.ErrorsList;
import br.com.mocamorena.view.StateEntityWindow;
import br.com.mocamorena.view.UserError;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class ChangePasswordDialog extends javax.swing.JDialog {

    private Usuario usuario;
    private final static String titleWindow = "Usuário";
    private StateEntityWindow stateEntity;

    public ChangePasswordDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Usuario usuario) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setUsuario(usuario);
        setLocationRelativeTo(null);
        organizeWindow();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nomeField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        loginField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        senhaField = new javax.swing.JPasswordField();
        senhaErrorLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        novaSenhaField = new javax.swing.JPasswordField();
        novaSenhaErrorLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        codigoLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome:");

        nomeField.setEditable(false);
        nomeField.setFocusable(false);

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Login:");

        loginField.setEditable(false);
        loginField.setFocusable(false);

        jLabel3.setText("Senha:");

        senhaErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        jLabel4.setText("Nova senha:");

        novaSenhaErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        jLabel5.setText("Código:");

        codigoLabel.setText("0");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(122, Short.MAX_VALUE)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addGap(78, 78, 78))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(novaSenhaField, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(novaSenhaErrorLabel))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(loginField)
                        .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(senhaField, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(senhaErrorLabel))
                    .addComponent(codigoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(codigoLabel)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(senhaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(senhaErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(novaSenhaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addComponent(novaSenhaErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            ControleUsuario controle = new ControleUsuario();
            String login = loginField.getText();
            String password = String.valueOf(senhaField.getPassword());
            Usuario user = controle.authenticateUser(login, password);
            if (user != null) {
                if (getStateEntity() == StateEntityWindow.CHANGEPASSWORD) {
                    controle.trocarSenha(objetoUsuario().getId(),
                            String.valueOf(novaSenhaField.getPassword()));
                    JOptionPane.showMessageDialog(this, "A senha foi trocada com sucesso.", "Mensagem do sistema", 1);
                }
            } else {
                JOptionPane.showMessageDialog(this, "A senha atual não foi informada corretamente.", "Mensagem do sistema", 0);
                senhaField.setText(null);
                senhaField.requestFocus();
                return;
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel codigoLabel;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField loginField;
    private javax.swing.JTextField nomeField;
    private javax.swing.JLabel novaSenhaErrorLabel;
    private javax.swing.JPasswordField novaSenhaField;
    private javax.swing.JLabel senhaErrorLabel;
    private javax.swing.JPasswordField senhaField;
    // End of variables declaration//GEN-END:variables

    private void setUsuario(Usuario usuario) {
        if (usuario == null) {
            return;
        }
        this.usuario = usuario;
        codigoLabel.setText(String.valueOf(usuario.getId()));
        nomeField.setText(usuario.getNome());
        loginField.setText(usuario.getLogin());
    }

    private void organizeWindow() {
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if ((senhaField.getPassword().length < 3) || (senhaField.getPassword().length > 12)) {
            errorsList.addError(new UserError(senhaErrorLabel, "A senha do usuário deve ter entre 3 e 12 dígitos."));
        }
        if ((novaSenhaField.getPassword().length < 3) || (novaSenhaField.getPassword().length > 12)) {
            errorsList.addError(new UserError(novaSenhaErrorLabel, "A nova senha do usuário deve ter entre 3 e 12 dígitos."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }

    private void isShowErrorsLabel(boolean show) {
        senhaErrorLabel.setVisible(show);
        novaSenhaErrorLabel.setVisible(false);
    }

    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }

    public Usuario objetoUsuario() {
        return usuario;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
